#include <gflags/gflags.h>
#include <json/json.h>

#include <memory>
#include <thread>

#include "../../common/elastic.h"
#include "../../common/log.h"

DEFINE_int32(level, 1, "日志等级");
DEFINE_bool(mode, false, "调试模式-false, 发布模式-true");
DEFINE_string(path, "./logfile", "发布模式下日志输出到的文件路径");

int main(int argc, char* argv[]) {
    gflags::ParseCommandLineFlags(&argc, &argv, true);
    chat::initLogger(FLAGS_level, FLAGS_mode, FLAGS_path);

    std::vector<std::string> hosts = {"http://127.0.0.1:9200/"};
    std::shared_ptr<elasticlient::Client> client =
        std::make_shared<elasticlient::Client>(hosts);

    // 1. 创建索引和映射
    chat::ESIndex es_index(client, "hello", "_doc");
    es_index.append("nickname", "text", "ik_max_word", true);
    if (!es_index.create()){
        LOG_ERROR("索引创建失败");
        return -1;
    }

    // 2. 向映射添加字段
    chat::ESInsert es_insert(client, "hello", "_doc");
    es_insert.append("nickname", "张三");
    if (!es_insert.insert("0000001")){
        LOG_ERROR("数据新增失败");
        return -1;
    }

    std::this_thread::sleep_for(std::chrono::seconds(1));

    // 3. 修改映射字段
    es_insert.append("nickname", "李四");
    if (!es_insert.insert("0000001")){
        LOG_ERROR("数据修改失败");
        return -1;
    }

    std::this_thread::sleep_for(std::chrono::seconds(1));

    // 4. 查找
    chat::ESSearch es_search(client, "hello", "_doc");
    es_search.appendShouldMatch("nickname.keyword", "李四");
    es_search.appendMustNotTerm("nickname.keyword", {"李四"});
    Json::Value root = es_search.search();
    if (root.empty()) {
        LOG_ERROR("结果为空");
        return -1;
    }

    if (root.isArray() == false){
        LOG_ERROR("搜索结果不是数组");
        return -1;
    }

    for (unsigned int i = 0; i < root.size(); ++i){
        LOG_DEBUG("nickname: {}", root[i]["_source"]["nickname"].asString());
    }

    // 4. 删除索引
    chat::ESRemove es_remove(client, "hello", "_doc");
    if (!es_remove.remove("0000001")){
        LOG_ERROR("删除索引失败");
        return -1;
    }

    return 0;
}